<template>
  <a-input v-model:value="data" readonly placeholder="请选择" @click="onClick">
    <template #suffix>
      <EnvironmentOutlined />
    </template>
  </a-input>
  <a-modal width="848px" v-model:open="modal" title="地址选择器" @cancel="onCancel" @ok="onOk">

    <template #footer>
      <div class="flex-row">
        <div class="flex1" style="text-align: start;line-height: 32px;">
          注：点击地图选择坐标, 拖动图标修改坐标
        </div>
        <a-space>
          <a-button key="back" @click="onCancel">取消</a-button>
          <a-button key="submit" type="primary" @click="onOk">确定</a-button>
        </a-space>
      </div>
    </template>

    <AddressSelect :value="selectValue" @update:value="onAddressUpdate" />


    <div style="height:400px; width:800px" class="posr mt">
      <l-map ref="map" v-model:zoom="zoom" :center="center" v-if="modal" :useGlobalLeaflet="false" @click="onMapClick"
        @mousemove="onMouseMove" @ready="onMapReady">
        <l-tile-layer
          url="http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}"
          layer-type="base" name="autonavi"></l-tile-layer>
        <l-marker :lat-lng="markerLatlng" ref="marker" v-if="markerLatlng" :draggable="true" @moveend="onMarkerMoved"
          @add="onMarkerAdd" />
      </l-map>
    </div>
    <div class="mt flex-row gap">
      <a-input style="width: 260px;" readonly
        :value="markerLatlng ? `${markerLatlng.lat.toFixed(4)},${markerLatlng.lng.toFixed(4)}` : ''"
        placeholder="请点击地图选择"></a-input>
      <div class="flex1">
        <a-spin :spinning="loading">
          <a-input v-model:value="address" placeholder="请输入地址" />
        </a-spin>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { nextTick, onMounted, ref, watch, toRaw } from 'vue'
import "leaflet/dist/leaflet.css";
import { LMap, LTileLayer, LMarker } from "@vue-leaflet/vue-leaflet";
import { message } from 'ant-design-vue';
import AddressSelect from './AddressSelect.vue';

const props = defineProps(['value'])
const emit = defineEmits(['update:value'])

const map = ref()
const zoom = ref(16)
const center = ref([29.41311005273475, 105.6040942668915])
const marker = ref()
const mapClicked = ref(false)
const markerLatlng = ref({
  lat: center.value[0],
  lng: center.value[1]
})
const loading = ref(false)
const address = ref()
const addressObj = ref()

const selectValue = ref()
const data = ref()
const modal = ref(false)

watch(() => props.value, (v) => {
  // console.log('address value ', v)
  parseProps()

})

onMounted(() => {
  parseProps()
})

const parseProps = () => {
  const v = props.value
  if (v == undefined) {
    data.value = undefined
  } else {
    data.value = v.address
    if (v.lat && v.lng) {
      center.value = [v.lat, v.lng]
      markerLatlng.value = {
        lat: v.lat,
        lng: v.lng
      }
      mapClicked.value = true;
    }
    if (v.address) {
      address.value = v.address
    }
    if (typeof v.province == 'string') {
      selectValue.value = [v.province, v.city, v.district]
    }
  }
}

const onMapReady = () => {
  console.log("map ready .")
}
const onMarkerAdd = () => {

  if (props.value.lat) {
    markerLatlng.value = {
      lat: props.value.lat,
      lng: props.value.lng
    }
  }

  const latlng = markerLatlng.value
  if (marker.value && latlng) {
    marker.value.leafletObject.setLatLng(latlng)
    map.value.leafletObject.panTo(latlng)
  }
}

const onClick = () => {
  modal.value = true
}
const onCancel = () => {
  modal.value = false
}
const onOk = () => {
  modal.value = false
  if (!markerLatlng.value) {
    message.warn('请在地图上点击获取地址坐标')
    return
  }
  if (!address.value) {
    message.warn('没有自动获取到地址描述，请手动填写')
    return
  }
  const obj = toRaw(addressObj.value)
  const rs = {
    lat: markerLatlng.value.lat,
    lng: markerLatlng.value.lng,
    address: address.value,
    // 额外
    province: obj?.province,
    city: obj?.city,
    district: obj?.district,
    adcode: obj?.district?.id,
  }
  console.log(rs)
  emit('update:value', toRaw(rs))

  data.value = rs.address
}
const onMouseMove = (e) => {
  const { latlng } = e;
  if (!mapClicked.value) {
    markerLatlng.value = latlng
  }
}
const onMapClick = (e) => {
  const { latlng } = e;
  mapClicked.value = true
  markerLatlng.value = latlng

}
const onMarkerMoved = (e) => {
  const latlng = e.target._latlng;
  markerLatlng.value = latlng

}

const onAddressUpdate = (e) => {
  addressObj.value = e;
  const { province, city, district } = e;
  const geo = district.geo;
  parseGeo(geo)

  let cname = '', dname = '';
  if (city.name.indexOf('城区') < 0 && city.name.indexOf('郊县') < 0 && city.name != province.name) {
    cname = city.name
  }
  if (district.name != city.name) {
    dname = district.name
  }

  address.value = province.name + (cname) + (dname)

}


const parseGeo = (geo) => {
  console.log(geo)
  const arr = geo.split(' ')
  const latlng = {
    lng: parseFloat(arr[0]),
    lat: parseFloat(arr[1]),
  }
  markerLatlng.value = latlng
  if (marker.value) {
    marker.value.leafletObject.setLatLng(latlng)
    map.value.leafletObject.panTo(latlng)
  }
  mapClicked.value = true;
}


</script>

<style lang="less" scoped>
.poi-list {
  position: absolute;
  z-index: 1000;
  top: 10px;
  right: 10px;
  padding: 12px;
  background-color: rgba(0, 0, 0, .5);
  height: 300px;
  overflow-y: auto;
  color: #fff;
  border-radius: 8px;

  .item {
    cursor: pointer;
    transition: .3s;
    margin-bottom: 6px;

    &:hover {
      text-shadow: 0 0 5px rgba(255, 255, 255, 0.5);
      transform: scale(1.02)
    }

    .name {
      margin-bottom: 2px;
    }

    .desc {
      padding-left: 1.4em;
      font-size: 0.8em;
      opacity: .7;
    }
  }
}
</style>